import Vue from 'vue';
import wx from 'we-jssdk';
import { DB } from '../config/db';
import _ from 'lodash/collection/';
import device from '../filter/device';
import { mapActions } from 'vuex'
import url from '../filter/url';
import wxEvent from '../filter/wxconfig.js';

export default {
	methods: {
		init(){
			return new Promise((resolve, reject) => {
				this.getActivityList().then(() => {
					if(!localStorage["hcxsq_current_city_info"]){
						this.getLocation().then((position) => {
							this.getCityName(position.latitude, position.longitude).then(() => {
								// 异步  可以执行 跳转逻辑
								// 动画结束 跳转
								setTimeout(() => {
									this.jumpAction();
								}, 4000);
								resolve(true);
							});
						});
					}else{
						let currentCity =  JSON.parse(localStorage["hcxsq_current_city_info"]);

						// 判断缓存中的当前城市 是否有活动
						let currentActivity = _.find(this.$store.state.activityList, {'cityCode': currentCity.cityCode});

						if(currentActivity && currentActivity.current && currentActivity.current.id){
							currentCity.startTime = currentActivity.current.startTime;

							localStorage["hcxsq_current_city_info"] = JSON.stringify(currentCity);

							this.$store.commit('setCurrentActivityInfo', currentActivity);

							this.$store.commit('setCurrentCityInfo', currentCity);
						}else{
							this.setCityDefault();
						}

						// 异步  可以执行 跳转逻辑
						setTimeout(() => {
							this.jumpAction();
						}, 4000);
						resolve(true);
					}
				});
			});
		},
		getLocation(){
			return new Promise((resolve, reject) => {
				if(device.isWeixin){
					wx.ready(() => {
						// 获取地理位置
						wx.getLocation({
			                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
			                success: res => {
			                    resolve({latitude:res.latitude,longitude:res.longitude});
			                },
			                fail: () => {
			                    resolve({latitude: 31.230416, longitude: 121.473701});
			                },
			                cancel: () => {
			                    //这个地方是用户拒绝获取地理位置
			                    // 默认上海
			                    resolve({latitude: 31.230416, longitude: 121.473701});
			                }
			            }); 
					});
				}else {
					// resolve({latitude: 31.230416, longitude: 121.473701});
					// 北京
					resolve({latitude:39.914889, longitude: 116.403874});
					
				}
			});
		},
		getCityName(lat, lng){
			return Vue.http.jsonp('https://apis.map.qq.com/ws/geocoder/v1/', {params: {
	                location: lat + ',' + lng,
	                key: 'M5JBZ-DL43P-FAZDH-LJOEB-4BZM2-KHBLJ',
	                output: 'jsonp',
	                get_poi: 1
	            }
	        }).then((res) => {
	            if (res.data.status == 0) {
	                let result = res.data.result;
	                let locationCity = result.address_component.city;
	                let currentCity = _.find(this.$store.getters.cityList, {'fullName': locationCity});

	                if(!currentCity){
	                    this.setCityDefault();
	                }else{
  						// 判断缓存中的当前城市 是否有活动
						let currentActivity = _.find(this.$store.state.activityList, {'cityCode': currentCity.cityCode});
						if(currentActivity && currentActivity.current){
							currentCity.startTime = currentActivity.current.startTime;

							this.$store.commit('setCurrentActivityInfo', currentActivity);

							this.$store.commit('setCurrentCityInfo', currentCity);

							localStorage["hcxsq_current_city_info"] = JSON.stringify(currentCity);
						}else{
	                    	this.setCityDefault();
						}
	                }

	            } else {
	                // 接口错误的情况 默认是列表中的第一个城市
	                this.setCityDefault();
	            }
	        }).catch(() => {
	            this.setCityDefault();
	        });
		},
		// 获取活动列表
		getActivityList(){
			return Vue.http.get(DB.ip + 'activity/list', {
				params: {
					openid: this.$store.state.userSubscribeInfo.openid
				}
			}).then((res) => {
				res = res.body;
				if(res.resCode == '000000'){
					// 测试
					this.$store.commit('setActivityData', res.datas);
					this.$store.commit('serverTime', res.currentTime);
					sessionStorage['hcxsq_servertime'] = new Date(res.currentTime.replace(/-/g, '/')).getTime();
				}else{
					this.$aui.toast.show(res.resMsg);
				}
			}, (error) => {
				this.$aui.toast.show('系统错误，请稍后再试！');
			});
		},
		// 设置默认城市
		setCityDefault(){
			if(!this.$store.state.activityList || this.$store.state.activityList.length <= 0){
				return;
			}
			let x = {}, index = 0;
			// 默认城市信息
			for(let i = 0; i < this.$store.state.activityList.length; i ++){
				if(this.$store.state.activityList[i].current && this.$store.state.activityList[i].current.id){
					x = {
						cityCode:this.$store.state.activityList[i].cityCode,
						cityName:this.$store.state.activityList[i].cityName,
						fullName: this.$store.state.activityList[i].cityName.length > 2? this.$store.state.activityList[i].cityName: this.$store.state.activityList[i].cityName + '市',
						startTime: this.$store.state.activityList[i].current? this.$store.state.activityList[i].current.startTime: ''
					}
					index = i;
					break;
				}
			}

			this.$store.commit('setCurrentCityInfo', x);

			localStorage["hcxsq_current_city_info"] = JSON.stringify(x);

			this.$store.commit('setCurrentActivityInfo', this.$store.state.activityList[index]);

		},
		...mapActions([
            'setUserInfo' // 映射 this.setUserInfo() 为 this.$store.dispatch('setUserInfo')
        ]),
        // 根据当前活动以及用户的关注绑定情况做不同的跳转
        jumpAction(){
            this.isHasAllActivity().then(() => {
            	// 在其他页面刷新也会跳转，所以判断一下当前的页面，只有从首页进入的才会判断
            	if(this.$route.name !== 'index'){
            		return;
            	}

                this.isJoin().then((userPrize) => {
                    if(userPrize.hasWin == 1){
                        this.$router.push({name: 'winner', query: {id: this.$store.state.currentActivityInfo.current.id, channel: this.$store.state.userSubscribeInfo.channel, activityId: this.$store.state.userSubscribeInfo.activityId, bind: this.$store.state.userSubscribeInfo.bind, subscribe: this.$store.state.userSubscribeInfo.subscribe, unionid: this.$store.state.userSubscribeInfo.unionid, openid: this.$store.state.userSubscribeInfo.openid }});
                    }else{
                        if(this.$store.state.ownPrizeInfo.next){
                            this.$router.push({name: 'end', params: {isFirst: 0}, query: {id: this.$store.state.currentActivityInfo.current.id,channel: this.$store.state.userSubscribeInfo.channel, activityId: this.$store.state.userSubscribeInfo.activityId, bind: this.$store.state.userSubscribeInfo.bind, subscribe: this.$store.state.userSubscribeInfo.subscribe, unionid: this.$store.state.userSubscribeInfo.unionid, openid: this.$store.state.userSubscribeInfo.openid  }});
                        }else{
                            this.$router.push({name: 'endno', params: { noCurrent: 0, isFirst: 0}, query: {id: this.$store.state.currentActivityInfo.current.id,channel: this.$store.state.userSubscribeInfo.channel, activityId: this.$store.state.userSubscribeInfo.activityId, bind: this.$store.state.userSubscribeInfo.bind, subscribe: this.$store.state.userSubscribeInfo.subscribe, unionid: this.$store.state.userSubscribeInfo.unionid, openid: this.$store.state.userSubscribeInfo.openid  }});
                        }
                    }
                }, () =>{
                    this.$router.push({name: 'activity', query: {channel: this.$store.state.userSubscribeInfo.channel, activityId: this.$store.state.userSubscribeInfo.activityId, bind: this.$store.state.userSubscribeInfo.bind, subscribe: this.$store.state.userSubscribeInfo.subscribe, unionid: this.$store.state.userSubscribeInfo.unionid, openid: this.$store.state.userSubscribeInfo.openid }});
                });
            }, () => {
                // noCurrent 说明 所有的城市都没有当前活动 所以直接进入结束页面
                if(this.$store.state.currentActivityInfo && this.$store.state.currentActivityInfo.current && this.$store.state.currentActivityInfo.current.id){
                	this.$router.push({name: 'endno', params: { noCurrent: 1, isFirst: 0 }, query: {id: this.$store.state.currentActivityInfo.current.id, channel: this.$store.state.userSubscribeInfo.channel, activityId: this.$store.state.userSubscribeInfo.activityId, bind: this.$store.state.userSubscribeInfo.bind, subscribe: this.$store.state.userSubscribeInfo.subscribe, unionid: this.$store.state.userSubscribeInfo.unionid, openid: this.$store.state.userSubscribeInfo.openid }});
                }else{
                	this.$router.push({name: 'endno', params: { noCurrent: 1, isFirst: 0 }, query: {channel: this.$store.state.userSubscribeInfo.channel, activityId: this.$store.state.userSubscribeInfo.activityId, bind: this.$store.state.userSubscribeInfo.bind, subscribe: this.$store.state.userSubscribeInfo.subscribe, unionid: this.$store.state.userSubscribeInfo.unionid, openid: this.$store.state.userSubscribeInfo.openid }});
                }
            });
        },
        // 判断是否所有城市都没有当前活动，如果没有，就显示
        isHasAllActivity(){
            return new Promise((resolve, reject) => {
                let activityInfo = this.$store.state.activityList;
                let hasCurrentActivity = false;
                for(let i = 0; i < activityInfo.length; i ++){
                    if(activityInfo[i] && activityInfo[i].current && activityInfo[i].current.id){
                        hasCurrentActivity = true;
                        break;
                    }
                }
                if(hasCurrentActivity){
                    resolve(hasCurrentActivity);
                }else{
                    reject(hasCurrentActivity);
                }
            });
        },
        // 判断是否参与
        isJoin(){
            return new Promise((resolve, reject) => {
                let activityInfo = this.$store.state.activityList;
                let isJoin = false, activityId = '';
                for(let i = 0; i < activityInfo.length; i ++){
                    if(activityInfo[i].current && activityInfo[i].current.isJoin){
                        isJoin = true;
                        activityId = activityInfo[i].current.id;
                        break;
                    }
                }
                if(isJoin){
                    this.getOwnPrizeInfo(activityId, resolve, reject);
                }else{
                    reject(false);
                }
            });
        },
        // 对于已经参与的用户，再次进入查看自己的结果信息
        getOwnPrizeInfo(id, resolve, reject){
            return this.$http.get(DB.ip + 'activity/'+ id +'/join', {
                params: {
                    openid: this.$store.state.userSubscribeInfo.openid
                }
            }).then((res) => {
                if(res.data.resCode == '000000'){
                    res.data.data.currentActivityId = id;
                    this.$store.commit('setOwnPrizeInfo', res.data.data);
                    resolve(res.data.data);
                }else{  
                    this.$aui.toast.show(res.data.resMsg);
                }
            }, (error) => {
                this.$aui.toast.show('系统错误，错误代码：' + error.status)
            });
        }
	},
	created(){
		this.setUserInfo({
            channel: url.getQueryString('channel') || '105',
            openid: url.getQueryString('openid') || 'ohryYtwcni4p1mpuw-F-fKAVAH0I', // 测试
            unionid: url.getQueryString('unionid') || '',
            bind: url.getQueryString('bind') || '',
            subscribe: url.getQueryString('subscribe') || '',
            activityId: url.getQueryString('activityId') || ''
        });
		
		this.init();
	}
}